import json
from loguru import logger

from model.pulsar_cluster import PulsarCluster


class ClusterManageService:
    """
    集群管理服务
    """

    def __init__(self):
        self.on_cluster_changed = None  # 初始化为 None
        self.init_from_file()

    def get_cluster_list(self):
        """
        获取集群树节点
        :return:
        """
        return self.cluster_list

    def add(self, pulsar_cluster):
        if pulsar_cluster.name is None:
            return Exception("名称不能为空")
        if pulsar_cluster.pulsar_addr is None:
            return Exception("pulsar地址不能为空")
        if pulsar_cluster.admin_addr is None:
            return Exception("admin地址不能为空")
        self.cluster_list.append(pulsar_cluster)
        if self.on_cluster_changed:
            self.on_cluster_changed()  # 调用回调函数通知界面刷新

    def update(self, pulsar_cluster):
        if pulsar_cluster.name is None:
            return Exception("名称不能为空")
        if pulsar_cluster.pulsar_addr is None:
            return Exception("pulsar地址不能为空")
        if pulsar_cluster.admin_addr is None:
            return Exception("admin地址不能为空")
        for cluster in self.cluster_list:
            if str(cluster.id) == pulsar_cluster.id:
                cluster.name = pulsar_cluster.name
                cluster.pulsar_addr = pulsar_cluster.pulsar_addr
                cluster.admin_addr = pulsar_cluster.admin_addr
                if self.on_cluster_changed:
                    self.on_cluster_changed()  # 调用回调函数通知界面刷新
                return
        return Exception("集群不存在")

    def write_to_file(self):
        """
        将配置持久化到文件中

        :rtype: object
        """
        clusters_data = [
            {
                "id": cluster.id,
                "name": cluster.name,
                "pulsar_addr": cluster.pulsar_addr,
                "admin_addr": cluster.admin_addr
            } for cluster in self.cluster_list
        ]

        with open('clusters.json', 'w', encoding='utf-8') as f:
            json.dump(clusters_data, f, ensure_ascii=False, indent=4)

    def init_from_file(self):
        """
        读取配置文件中的内容
        :return:
        """
        try:
            with open('clusters.json', 'r', encoding='utf-8') as f:
                clusters_data = json.load(f)
                logger.info("load cluster data : {}", clusters_data)
                self.cluster_list = [
                    PulsarCluster(**data) for data in clusters_data
                ]
            if self.on_cluster_changed:
                self.on_cluster_changed()  # 调用回调函数通知界面刷新
        except FileNotFoundError:
            print("配置文件不存在，创建新的文件并初始化为空集合")
            self.cluster_list = []
            self.write_to_file()  # 创建一个新的文件并保存空集合
        except json.JSONDecodeError:
            print("配置文件格式错误")
